package com.peng.leetcode.array;

/**
 * NumIslands
 * 200. 岛屿数量
 * https://leetcode.cn/problems/number-of-islands/
 *
 * @author: lupeng6
 * @create: 2023/2/16 18:00
 */
public class NumIslands {
    private boolean[][] visited;
    private int ans = 0;
    public int numIslands(char[][] grid) {
        visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    ans++;
                    fill(grid, i, j);
                }
            }
        }
        return ans;
    }

    void fill(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || visited[i][j]) {
            return;
        }
        if (grid[i][j] == '1') {
            visited[i][j] = true;
            fill(grid, i, j + 1);
            fill(grid, i, j - 1);
            fill(grid, i + 1, j);
            fill(grid, i - 1, j);
        }
    }
}
